import DataStore from "./base/DataStore.js"
import UpPencil from "./runtime/UpPencil.js"
import DownPencil from "./runtime/DownPencil.js"

class Director {
  constructor() {
    this.dataStore = DataStore.getInstance()
    this.moveSpeed = 2
  }

  createPencil() {
    const minTop = window.innerHeight / 8
    const maxTop = window.innerHeight / 2
    const top = minTop + Math.random() * (maxTop - minTop)
    this.dataStore.get("pencils").push(new UpPencil(top))
    this.dataStore.get("pencils").push(new DownPencil(top))
  }

  static getInstance() {
    if (!Director.instance) {
      Director.instance = new Director()
    }
    return Director.instance
  }
  static isStrike(mbirds, mpencils) {
    let s = false
    if (
      mbirds.right < mpencils.left||
      mbirds.left > mpencils.right ||
      mbirds.top > mpencils.bottom ||
      mbirds.bottom < mpencils.top
    ) {
      console.log("没撞到")
      s = true
    }
    return !s
  }
  birdsEvent() {
    this.dataStore.get("birds").y = this.dataStore.get("birds").birdsY
    this.dataStore.get("birds").time = 0
  }
  check() {
    const birds = this.dataStore.get("birds")
    const pencils = this.dataStore.get("pencils")
    const score = this.dataStore.get("score")
    if (birds.birdsY + birds.h >= this.dataStore.get("land").y) {
      console.log("游戏结束")
      this.gameover = true
    }
    const birdsBorder = {
      left: birds.x,
      right: birds.x + birds.w,
      top: birds.birdsY,
      bottom: birds.birdsY + birds.h
    }
    const len = pencils.length

    for (let i = 0; i < len; i++) {
      const pencilBorder = {
        left: pencils[i].x,
        right: pencils[i].x + pencils[i].w,
        top: pencils[i].y,
        bottom: pencils[i].y + pencils[i].sh
      }
      if (Director.isStrike(birdsBorder, pencilBorder)) {
        console.log("撞击")
        this.gameover = true
      }
    }
    if(birds.x>pencils[0].x+pencils[0].w&&score.addScore){
      score.addScore = false
      score.scoreNumber++
    }
  }
  run() {
    if (!this.gameover) {
      this.check()

      const pencils = this.dataStore.get("pencils")
      if (pencils[0].x + pencils[0].w <= 0 && pencils.length === 4) {
        pencils.shift()
        pencils.shift()
        this.dataStore.get("score").addScore = true
      }
      if (pencils[0].x <= (window.innerWidth - pencils[0].w) / 2 && pencils.length === 2) {
        this.createPencil()
      }
      this.dataStore.get("background").draw()
      this.dataStore.get("pencils").forEach(function (value, index, arr) {
        value.draw()
      })
      this.dataStore.get("land").draw()
      this.dataStore.get("birds").draw()
      this.dataStore.get("score").draw()
      let timer = requestAnimationFrame(() => { this.run() })
      this.dataStore.put("timer", timer)
    } else {
      cancelAnimationFrame(this.dataStore.get("timer"))
      this.dataStore.get("startButton").draw()
      this.dataStore.destroy()
    }
  }
}

export default Director
